﻿using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.Samples.ServiceHosting.AspProviders;
using Log = Microsoft.Samples.ServiceHosting.HelloFabric.ApplicationEnvironment;

namespace BlogEngine.Core.Azure.BlogProvider
{
    public class FileStorage
    {
        private BlobProvider _provider;
        private BlobProvider Provider
        {
            get
            {
                if (_provider == null)
                {
                    var containerName = StorageAccountInfo.GetConfigurationSetting("BlobContainerName", null, true);
                    _provider = new BlobProvider(StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration(), containerName);
                }
                return _provider;
            }
        }


        public Stream Load(string path)
        {
            if (path.StartsWith("/"))
                path = path.Substring(1);

            if (Exists(path))
                return new MemoryStream((byte[])HttpRuntime.Cache[path]);

            return null;
        }

        public void Save(string path, Stream file)
        {
            if (path.StartsWith("/"))
                path = path.Substring(1);

            Provider.UploadStream(path, file);
        }

        public bool Exists(string path)
        {
            if (path.StartsWith("/"))
                path = path.Substring(1);

            if (HttpRuntime.Cache[path] != null)
                return true;
            return RefreshItem(path);
        }


        private bool RefreshItem(string path)
        {
            MemoryStream ms = LoadItem(path);
            if (ms == null)
                return false;

            byte[] buf = ms.ToArray();
            ms.Close();

            HttpRuntime.Cache.Insert(path, buf, null,
                Cache.NoAbsoluteExpiration, TimeSpan.FromHours(4), // TODO: Add a config setting for this
                CacheItemPriority.Default, null);

            return true;
        }

        private MemoryStream LoadItem(string path)
        {
            try
            {
                BlobProperties prop;
                return Provider.GetBlobContent(path, out prop);
            }
            catch (Exception e)
            {
                Log.LogWarning("Could not load file: " + path + "!"
                    + Environment.NewLine + e);

                return null; // Probably doesn't exist (widgets expects this behaviour)
            }
        }
    }
}
